#include <QDir>
#include <mediamodel.h>
#include <QDebug>
#include <QUrl>
Media::Media(const QString &name, const QString &url):
    m_name(name),
    m_url(url)
{
}

QString Media::name() const
{
    return m_name;
}
QString Media::url() const{
    return m_url;
}

MediaModel::MediaModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

void MediaModel::addMedia(const Media &media)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_medias << media;
    endInsertRows();
}

int MediaModel::rowCount(const QModelIndex & parent) const {
    Q_UNUSED(parent);
    return m_medias.count();
}

QVariant MediaModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= m_medias.count())
        return QVariant();

    const Media &media = m_medias[index.row()];
    if (role == NameRole)
        return media.name();
    else if (role == UrlRole)
        return media.url();
    return QVariant();
}

void MediaModel::importFolder(QString folder)
{
    QDir dir(QUrl(folder).toLocalFile());
    dir.setFilter(QDir::Files);
    QFileInfoList files = dir.entryInfoList();
    QListIterator<QFileInfo> iter(files);
    while(iter.hasNext()){
        QFileInfo file = iter.next();
        qDebug() << file.fileName();
        addMedia(Media(file.baseName(),file.filePath()));
    }
}

QString MediaModel::getUrl(int index) const
{
    return m_medias[index].url();
}

QString MediaModel::getName(int index) const
{
    return m_medias[index].name();
}


QHash<int, QByteArray> MediaModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[NameRole] = "name";
    roles[UrlRole] = "url";
    return roles;
}
